<template>
  <el-dialog
    custom-class="add-office-staff-reim"
    v-el-drag-dialog="{ drag: true, full: false, resize: false }"
    title="新增办公室报账"
    :close-on-click-modal="false"
    :visible="true"
    @close="closeMd"
    width="70%"
    append-to-body>
    <el-button 
      style="margin-bottom: 10px" 
      type="primary" 
      icon="el-icon-circle-plus-outline" 
      @click="handleAdd">
      添加
    </el-button>

    <el-form 
      :model="sourceData" 
      ref="formRef">
      <el-table
        ref="tableRef"
        :data="sourceData.tableData"
        border fit
        height="400">
        <el-table-column label="经办人">
          <template slot-scope="scope">
            <el-form-item 
              :prop="'tableData.' + scope.$index + '.operUname'"
              :rules="[{ required: true, message: '请选择金额类型', trigger: 'change' }]">
              <el-select 
                v-model="scope.row.operUname" 
                clearable 
                filterable 
                placeholder="经办人">
                <el-option 
                  v-for="item in serviceManList"
                  :key="item.baseUserId.uname"
                  :label="item.baseUserId.realName"
                  :value="item.baseUserId.uname">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="收款人">
          <template slot-scope="scope">
            <el-form-item 
              :prop="'tableData.' + scope.$index + '.cusUname'"
              :rules="[{ required: false, message: '请选择收款人', trigger: 'change' }]">
              <el-select 
                v-model="scope.row.cusUname"
                clearable filterable
                remote reserve-keyword
                :remote-method="remoteMethod"
                :loading="filter_loading"
                placeholder="收款人">
                <el-option 
                  v-for="item in cusUnameOptions"
                  :key="item.baseUserId && item.baseUserId.uname"
                  :label="item.baseUserId &&item.baseUserId.realName"
                  :value="item.baseUserId && item.baseUserId.uname">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="车牌号">
          <template slot-scope="scope">
            <el-form-item 
              :prop="'tableData.' + scope.$index + '.plateNum'"
              :rules="[{ required: false, message: '请选择车牌号', trigger: 'change' }]">
              <el-select 
                v-model="scope.row.plateNum" 
                clearable filterable 
                placeholder="车牌号">
                <el-option 
                  v-for="item in carNumList" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="收入金额">
          <template slot-scope="scope">
            <el-form-item 
              :prop="'tableData.' + scope.$index + '.jfMoney'"
              :rules="[
                { required: false, message: '请输入收入金额', trigger: 'blur' },
                { validator: validators, trigger: 'blur' }
              ]">
              <el-input v-model="scope.row.jfMoney"></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="支出金额">
          <template slot-scope="scope">
            <el-form-item 
              :prop="'tableData.' + scope.$index + '.dfMoney'"
              :rules="[
                { required: false, message: '请输入支出金额', trigger: 'blur' },
                { validator: validators, trigger: 'blur' }
              ]">
              <el-input v-model="scope.row.dfMoney"></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="记账类型">
          <template slot-scope="scope">
            <el-form-item 
              :prop="'tableData.' + scope.$index + '.reimTypeId'"
              :rules="[{ required: true, message: '请选择记账类型', trigger: 'change' }]">
              <el-select 
                v-model="scope.row.reimTypeId" 
                clearable filterable 
                placeholder="记账类型">
                <el-option 
                  v-for="item in reimTypeOptions" 
                  :key="item.id" 
                  :label="item.typeName" 
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="图片">
          <template slot-scope="scope">
            <el-form-item 
              :prop="'tableData.' + scope.$index + '.imgUrls'"
              :rules="[{ required: false, message: '请上传报账图片', trigger: 'change' }]">
              <UploadImg
                class="my-upload-img"
                :imgName="scope.row.imgUrls"
                @getImgUrl="(data) => setImgUrl(data,scope)"
                :url="'/company/upload'"
                :ps="{ userName: uname }"
                :icon="'凭证图片'"
              />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="摘要">
          <template slot-scope="scope">
            <el-form-item 
              :prop="'tableData.' + scope.$index + '.remark'"
              :rules="[{ required: true, message: '摘要', trigger: 'blur' }]">
              <el-input 
                v-model="scope.row.remark">
              </el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button 
              icon="el-icon-delete" 
              type="danger" 
              @click="handleDelete(scope)">
              删 除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <div class="fm-btn-row">
      <el-button 
        :loading="loading" 
        style="margin-left: 20px" 
        type="primary" 
        icon="el-icon-s-order"
        @click="handleAccount">
        立即申请
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import {mapGetters} from "vuex";
import elDragDialog from "@/directive/el-drag-dialog";
import {addStaffReimburse} from "@/api/services/order.service";
import {getAllPlateNum} from "@/api/services/logistics.service";
import UploadImg from '@/components/UploadImg';
import {getReimTypeDict, getStaffCombo, getCompanyCusList} from "@/api/services/common.service";

export default {
  name: "AddOfficeStaffReim",
  directives: {elDragDialog},
  components: {UploadImg},
  computed: {
    ...mapGetters(["uname"]),
  },
  data() {
    const validators = (rule, value, callback) => {
      if (value) {
        if (!this.FV.isFloat(value)) {
          return callback(new Error('金额格式错误'));
        }
        if (value <= 0) {
          return callback(new Error('金额不能小于0'));
        }
      }
      callback();
    }
    return {
      validators,
      filter_loading: false,
      loading: false,
      md: {state: this.state},
      sourceData: {
        tableData: [
          {
            reimTypeId: '', //报账类型id
            operUname: '', // 经办人uname
            cusUname: '', // 往来客户uname
            plateNum: '',  // 车牌号
            jfMoney: '',  // 收入金额
            dfMoney: '',  // 支出金额
            remark: '',  // 摘要
            imgUrls: '',  // 图片url
          }
        ]
      },
      bankOptions: [],
      reimTypeOptions: [], // 报账类型
      carNumList: [], // 车牌号
      serviceManList: [], // 经办人
      cusUnameOptions: [], // 收款人
    };
  },
  created() {
    this.init();
  },
  methods: {
    closeMd() {
      this.$emit("myClick", {state: false});
    },
    handleAdd() {
      this.sourceData.tableData.push({
        reimTypeId: '', //报账类型id
        operUname: '', // 经办人uname
        cusUname: '', // 往来客户uname
        plateNum: '',  // 车牌号
        jfMoney: '',  // 收入金额
        dfMoney: '',  // 支出金额
        remark: '',  // 摘要
        imgUrls: '',  // 图片url
      })
    },

    init() {
      // 报账类型
      getReimTypeDict({addWay: 0, type: 1}).then(res => {
        this.reimTypeOptions = res.data
      })
      // 车牌号
      getAllPlateNum({status: 0}).then(res => {
        this.carNumList = Object.keys(res.plateNums).map((item) => ({
          label: item,
          value: item,
        }));
      })
      // 员工下拉(经办人)
      getStaffCombo({staffState: "NORMAL,TRY"}).then((res) => {
        this.serviceManList = res.data || [];
        // console.log('经办人：', res.data)
      });
    },

    remoteMethod(query) {
      if (!query) {
        this.filter_loading = false
        this.cusUnameOptions = []
        return
      }
      this.filter_loading = true
      // 客户下拉(收款人)
      getCompanyCusList({find: query}).then(res => {
        this.filter_loading = false
        this.cusUnameOptions = res.data
      }).catch(() => {
        this.filter_loading = false
      })
    },

    setImgUrl(data, {$index}) {
      this.$set(this.sourceData.tableData[$index], 'imgUrls', data.url);
      this.U.clearFmVali(this, 'formRef', `tableData.${$index}.imgUrls`);
    },
    handleDelete({$index}) {
      this.sourceData.tableData.splice($index, 1)
    },

    async handleAccount() {
      const that = this, U = that.U, FV = that.FV;

      that.$refs.formRef.validate((valid) => {
        if(valid) {
          let fg = true;

          let list = that.sourceData.tableData;

          if(fg){
            for(let i = 0; i < list.length; i++){
              let o = list[i];
              if(!o.jfMoney && !o.dfMoney){
                fg = U.qerror(`第${i+1}行的<b>[收入金额]和[支出金额]</b>任填其一`, 5000);
                break;
              }else {
                if(FV.trimAll(o.jfMoney) == '') o.jfMoney = 0;
                if(FV.trimAll(o.dfMoney) == '') o.dfMoney = 0;

                o.jfMoney = FV.trimAll(o.jfMoney);
                o.dfMoney = FV.trimAll(o.dfMoney);
              }
            }
          }

          if(fg){
            let params = {staffReimInfo: list}
            that.loading = true
            addStaffReimburse(params).then(res => {
              that.loading = false
              if (res.code !== 1) {
                return U.qerror(res.msg);
              }
              that.closeMd();
              that.$emit("reloadDg");
            });
          }
        }
      })

    }
  },
};
</script>
